package com.cx.mall.common.util;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

@Data
@NoArgsConstructor
@Component
public class GetIpAddress {

    // 获取本机IP地址
    public static String getLocalIP() {
        try {
            // 方法1：简单方式获取IP
            String ip1 = InetAddress.getLocalHost().getHostAddress();
            System.out.println("方法1获取的IP: " + ip1);

            // 方法2：遍历网络接口获取IP
            String ip2 = getIpFromNetworkInterfaces();
            System.out.println("方法2获取的IP: " + ip2);

            return ip2;
        } catch (Exception e) {
            e.printStackTrace();
            return "无法获取IP地址";
        }
    }

    // 遍历网络接口获取IP地址（排除回环地址和虚拟地址）
    private static String getIpFromNetworkInterfaces() throws SocketException {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

        while (interfaces.hasMoreElements()) {
            NetworkInterface ni = interfaces.nextElement();

            // 跳过回环接口、虚拟接口和未启用的接口
            if (ni.isLoopback() || ni.isVirtual() || !ni.isUp()) {
                continue;
            }

            Enumeration<InetAddress> addresses = ni.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();

                // 跳过IPv6地址和回环地址
                if (!addr.isLoopbackAddress() && addr.getHostAddress().indexOf(":") == -1) {
                    return addr.getHostAddress();
                }
            }
        }

        return "未找到有效IP地址";
    }

    // 获取外网IP地址（需要访问外部服务）
    public static String getExternalIP() {
        try {
            // 这里使用了一个示例API，实际使用时可能需要更换为可靠的服务
            java.net.URL url = new java.net.URL("https://api.ipify.org");
            java.util.Scanner s = new java.util.Scanner(url.openStream(), "UTF-8").useDelimiter("\\A");
            return s.hasNext() ? s.next() : "无法获取外网IP";
        } catch (Exception e) {
            e.printStackTrace();
            return "获取外网IP失败";
        }
    }


}
